package com.exam.api.vo;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.exam.api.common.MyThreadLocal;
import com.exam.api.dto.ExamDetailDTO;
import com.exam.api.dto.QuestionsDTO;
import com.exam.api.service.ExamDetailService;
import com.exam.api.service.QuestionsService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: excel读取器
 * @author: fyy
 * @create: 2025/3/7 15:24
 **/
@Component
public class ExcelListener extends AnalysisEventListener<StuQuestionVO> {

    private List<ExamDetailDTO> examDetailDTOS = new ArrayList<>();// 临时存储


    @Override
    public void invoke(StuQuestionVO stuQuestionVO, AnalysisContext analysisContext) {
        String str = MyThreadLocal.get();
        String[] split = str.split("-");
        // 校验数据
        QuestionsService questionsService = SpringUtil.getBean(QuestionsService.class);
        ExamDetailDTO examDetailDTO = new ExamDetailDTO();
        examDetailDTO.setExamId(Long.parseLong(split[0]));
        examDetailDTO.setStudentId(Long.parseLong(split[1]));
        examDetailDTO.setQuestionId(stuQuestionVO.getQuestionId());
        examDetailDTO.setAnswer(stuQuestionVO.getAnswer()); // 保存 answer 字段
        examDetailDTO.setCreateTime(new Date());
        QuestionsDTO serviceById = questionsService.getById(stuQuestionVO.getQuestionId());
        if (serviceById == null) return;
        String answer = serviceById.getAnswer();
        if (StrUtil.isEmpty(answer)) return;
        if (StrUtil.isEmpty(stuQuestionVO.getAnswer())) return;
        if (answer.equals(stuQuestionVO.getAnswer())) {
            examDetailDTO.setGrade(serviceById.getGrade().toString());
        } else {
            examDetailDTO.setGrade("0");
        }
        examDetailDTOS.add(examDetailDTO);
    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        ExamDetailService orderInfoService = SpringUtil.getBean(ExamDetailService.class);
        orderInfoService.saveBatch(examDetailDTOS);
    }


}

